package com.ywd.platform.websocket.test;

import jakarta.websocket.*;

import java.net.URI;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicReference;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

@ClientEndpoint
public class WebSocketClient {

    private static final String WS_URL = "ws://192.168.124.8:13000/ws";
    private static final AtomicReference<Session> sessionRef = new AtomicReference<>();
    private static final Gson gson = new Gson();
    private static final String INITIAL_MESSAGE = "hello"; // 连接后自动发送的消息

    public static void main(String[] args) {
        try {
            // 1. 创建并连接WebSocket
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            container.connectToServer(WebSocketClient.class, new URI(WS_URL));

            // 2. 保持主线程活跃
            new Scanner(System.in).nextLine(); // 按回车退出
        } catch (Exception e) {
            System.err.println("[错误] 连接异常: " + e.getMessage());
        } finally {
            closeSession();
        }
    }

    @OnOpen
    public void onOpen(Session session) {
        sessionRef.set(session);
        System.out.printf("[WebSocket] 连接成功! 会话ID: %s%n", session.getId());

        // 连接成功后立即发送初始消息
        sendMessage(INITIAL_MESSAGE);
    }

    @OnMessage
    public void onMessage(String message) {
        try {
            if (isJson(message)) {
                JsonObject json = JsonParser.parseString(message).getAsJsonObject();
                printFormattedMessage("收到JSON消息", json);
            } else {
                printPlainMessage("收到文本消息", message);
            }
        } catch (Exception e) {
            System.err.println("[消息解析错误] " + e.getMessage());
        }
    }

    @OnClose
    public void onClose(CloseReason reason) {
        System.out.printf("[连接关闭] 原因: %s (代码: %d)%n",
                reason.getReasonPhrase(), reason.getCloseCode().getCode());
    }

    @OnError
    public void onError(Throwable error) {
        System.err.printf("[通信错误] %s%n", error.getMessage());
        error.printStackTrace();
    }

    // 辅助方法：发送消息
    public static void sendMessage(String message) {
        Session session = sessionRef.get();
        if (session != null && session.isOpen()) {
            try {
                session.getBasicRemote().sendText(message);
                System.out.printf("[已发送] %s%n", message);
            } catch (Exception e) {
                System.err.println("[发送失败] " + e.getMessage());
            }
        } else {
            System.err.println("[警告] 连接未就绪，消息未发送");
        }
    }

    // 辅助方法：安全关闭连接
    private static void closeSession() {
        Session session = sessionRef.get();
        if (session != null) {
            try {
                session.close(new CloseReason(
                        CloseReason.CloseCodes.NORMAL_CLOSURE,
                        "客户端主动退出"
                ));
            } catch (Exception e) {
                System.err.println("[关闭异常] " + e.getMessage());
            }
        }
    }

    // 辅助方法：检查字符串是否为JSON
    private boolean isJson(String str) {
        try {
            JsonParser.parseString(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    // 辅助方法：格式化打印JSON消息
    private void printFormattedMessage(String title, JsonObject json) {
        System.out.println("[" + title + "]");
        System.out.println("┌──────────────────────────");
        json.entrySet().forEach(entry ->
                System.out.printf("│ %-12s: %s%n", entry.getKey(), entry.getValue())
        );
        System.out.println("└──────────────────────────");
    }

    // 辅助方法：打印普通文本消息
    private void printPlainMessage(String title, String message) {
        System.out.printf("[%s] %s%n", title, message);
    }
}